package com.etoak.stock.security.service;

import com.etoak.stock.mapper.SysPermissionMapper;
import com.etoak.stock.mapper.SysRoleMapper;
import com.etoak.stock.mapper.SysUserMapper;
import com.etoak.stock.pojo.domin.MenuPermissionsDomain;
import com.etoak.stock.pojo.entity.SysPermission;
import com.etoak.stock.pojo.entity.SysRole;
import com.etoak.stock.pojo.entity.SysUser;
import com.etoak.stock.security.user.LoginUserDetail;
import com.etoak.stock.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.etoak.stock.service.impl.UserRoleServiceImpl.diGuiTree;


/**
 * @Author by 孙有泽
 * @Date 2024/11/10 10:28
 * @Description 定义用户详情服务bean
 */

@Service("userDetailsService")
public class LoginUserDetailService implements UserDetailsService {
    @Autowired
    private SysPermissionMapper  sysPermissionMapper;
    @Autowired
    UserService userService;

    @Autowired
    SysUserMapper sysUserMapper;



    /*
     * @author 孙有泽
     * @date 2024/12/23 13:15
     * @description 根据用户传入的相关详细信息 获取用户名 密文密码 权限集合
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库加载信息
        SysUser sysUser = userService.finUserInfoByUserName(username);
        if(sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //2.1组装UserDatils对象 需要的密文密码 权限集合（web接口绑定表示的集合）
        //2.2 其他字段 id email phone menus permissions

        //获取指定用户的权限集合 添加获取侧边栏数据和按钮的权限的结合信息
        List<SysPermission> perms =sysPermissionMapper.getPermissionListByUserId(sysUser.getId());
        //获取树状权限菜单数据
        List<MenuPermissionsDomain> menus =diGuiTree(perms, 0L);
        //获取菜单按钮集合
        List<String> authBtnPerms = perms.stream().
                filter(per -> !Strings.isNullOrEmpty(per.getCode()) && per.getType() == 3).
                map(per -> per.getCode()).collect(Collectors.toList());
        //获取springSecurity的权限集合 ROLE_角色信息+自身表示
        //用户拥有的所有的角色
        List<SysRole> roles= sysUserMapper.getRoleByUserId(sysUser.getId());
        List<String> ps=new ArrayList<>();
       perms.stream().forEach(per->{
            if (StringUtils.isNotBlank(per.getPerms())) {
                ps.add(per.getPerms());}
        });
        roles.stream().forEach(role->{
            ps.add("ROLE_"+role.getName());
       });
        String[] permStr=ps.toArray(new String[ps.size()]);
        System.out.println(permStr);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(permStr);
        LoginUserDetail loginUserDetail = new LoginUserDetail();
        BeanUtils.copyProperties(sysUser, loginUserDetail);
        loginUserDetail.setMenus(menus);
        loginUserDetail.setPermissions(authBtnPerms);
        loginUserDetail.setAuthorities(authorityList);
        return loginUserDetail;
    }
}

